<template>
  <div>
    <div class="login-container">
      <div class="login-box">
        <div class="title">
          <h2>你好,欢迎使用!</h2>
          <p>美遇校园二手商品交易平台</p>
        </div>

        <!-- 登录表单 -->
        <div v-show="!showRegisterForm">
          <div class="form-header">
            <h3>用户登录</h3>
          </div>

          <el-form
            ref="loginFormRef"
            :model="loginForm"
            :rules="loginRules"
            class="login-form"
          >
            <el-form-item prop="username">
              <el-input
                v-model="loginForm.username"
                placeholder="请输入账号"
                :prefix-icon="User"
              />
            </el-form-item>

            <el-form-item prop="password">
              <el-input
                v-model="loginForm.password"
                type="password"
                placeholder="请输入密码"
                :prefix-icon="Lock"
                show-password
              />
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                class="login-button"
                :loading="loading"
                @click="handleLogin"
                style="height: 40px; width: 100%; font-size: 16px"
              >
                登录
              </el-button>
            </el-form-item>

            <el-form-item>
              <div class="form-footer">
                <span>还没有账号？</span>
                <el-button type="text" @click="showRegisterForm = true"
                  >立即注册</el-button
                >
              </div>
            </el-form-item>
          </el-form>
        </div>

        <!-- 注册表单 -->
        <div v-show="showRegisterForm">
          <div class="form-header">
            <h3>用户注册</h3>
          </div>

          <el-form
            ref="registerFormRef"
            :model="registerForm"
            :rules="registerRules"
            class="register-form"
          >
            <el-form-item prop="userName">
              <el-input
                v-model="registerForm.userName"
                placeholder="请输入账户名"
                :prefix-icon="User"
              />
            </el-form-item>

            <el-form-item prop="userPassword">
              <el-input
                v-model="registerForm.userPassword"
                type="password"
                placeholder="请输入密码"
                :prefix-icon="Lock"
                show-password
              />
            </el-form-item>

            <el-form-item prop="confirmPassword">
              <el-input
                v-model="registerForm.confirmPassword"
                type="password"
                placeholder="请确认密码"
                :prefix-icon="Lock"
                show-password
              />
            </el-form-item>

            <el-form-item prop="userNickname">
              <el-input
                v-model="registerForm.userNickname"
                placeholder="请输入昵称"
                :prefix-icon="User"
              />
            </el-form-item>

            <el-form-item prop="userRealname">
              <el-input
                v-model="registerForm.userRealname"
                placeholder="请输入真实姓名"
                :prefix-icon="User"
              />
            </el-form-item>

            <el-form-item prop="userGender">
              <el-select
                v-model="registerForm.userGender"
                placeholder="请选择性别"
                style="width: 100%"
              >
                <el-option label="男" value="男" />
                <el-option label="女" value="女" />
              </el-select>
            </el-form-item>

            <el-form-item prop="userBirthday">
              <el-date-picker
                v-model="registerForm.userBirthday"
                type="date"
                placeholder="请选择出生日期"
                style="width: 100%"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>

            <el-form-item>
              <el-button
                type="success"
                class="register-button"
                :loading="registerLoading"
                @click="handleRegister"
                style="height: 40px; width: 100%; font-size: 16px"
              >
                注册
              </el-button>
            </el-form-item>

            <el-form-item>
              <div class="form-footer">
                <span>已有账号？</span>
                <el-button type="text" @click="showRegisterForm = false"
                  >立即登录</el-button
                >
              </div>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref } from "vue";
import { User, Lock } from "@element-plus/icons-vue";
import instance from "../../utils/request";
import router from "../../router/router";
import { ElMessage } from "element-plus";

// 控制显示注册表单还是登录表单
const showRegisterForm = ref(false);

// 登录表单引用
const loginFormRef = ref(null);

// 注册表单引用
const registerFormRef = ref(null);

// 登录加载状态
const loading = ref(false);

// 注册加载状态
const registerLoading = ref(false);

// 登录表单数据
const loginForm = reactive({
  username: "",
  password: "",
});

// 注册表单数据
const registerForm = reactive({
  userName: "",
  userPassword: "",
  confirmPassword: "",
  userNickname: "",
  userRealname: "",
  userGender: "",
  userBirthday: "",
});

// 登录表单验证规则
const loginRules = {
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, message: "密码长度不能小于6位", trigger: "blur" },
  ],
};

// 注册表单验证规则
const registerRules = {
  userName: [
    { required: true, message: "请输入账户名", trigger: "blur" },
    { min: 3, max: 20, message: "账户名长度应在3-20个字符之间", trigger: "blur" },
  ],
  userPassword: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, message: "密码长度不能小于6位", trigger: "blur" },
  ],
  confirmPassword: [
    { required: true, message: "请确认密码", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.userPassword) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  userNickname: [
    { required: true, message: "请输入昵称", trigger: "blur" },
    { min: 2, max: 20, message: "昵称长度应在2-20个字符之间", trigger: "blur" },
  ],
  userRealname: [{ required: true, message: "请输入真实姓名", trigger: "blur" }],
  userGender: [{ required: true, message: "请选择性别", trigger: "change" }],
  userBirthday: [{ required: true, message: "请选择出生日期", trigger: "change" }],
};

// 登录处理
const handleLogin = async () => {
  loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      try {
        const res = await instance.post("/user/login", loginForm);
        if (res.data.code === 200) {
          // console.log(res.data);
          sessionStorage.setItem("adminName", res.data.data.admin.adminNickname);
          sessionStorage.setItem("adminId", res.data.data.admin.id);

          router.push("/layoutSystem");
          // 强制刷新
          ElMessage.success("登录成功");
        } else if (res.data.code === 100) {
          // console.log(res.data);
          sessionStorage.setItem("userNickName", res.data.data.user.userNickname);
          sessionStorage.setItem("userId", res.data.data.user.id);
          console.log(sessionStorage.getItem("userNickName"));
          console.log(sessionStorage.getItem("userId"));
          router.push("/");
          // 强制刷新
          ElMessage.success("登录成功");
        } else {
          ElMessage.error(res.data.message || "登录失败");
        }
      } catch (error) {
        console.error("登录出错:", error);
        ElMessage.error("登录失败，请稍后再试");
      } finally {
        loading.value = false;
      }
    }
  });
};

// 注册处理
const handleRegister = async () => {
  registerFormRef.value.validate(async (valid) => {
    if (valid) {
      registerLoading.value = true;
      try {
        // 构造注册请求数据
        const registerData = {
          userName: registerForm.userName,
          userPassword: registerForm.userPassword,
          userNickname: registerForm.userNickname,
          userRealname: registerForm.userRealname,
          userGender: registerForm.userGender,
          userBirthday: registerForm.userBirthday,
        };

        const res = await instance.post("/user/register", registerData);
        if (res.data.code === 200) {
          ElMessage.success("注册成功");
          // 注册成功后切换到登录表单
          showRegisterForm.value = false;
          // 清空注册表单
          Object.keys(registerForm).forEach((key) => {
            registerForm[key] = "";
          });
        } else {
          ElMessage.error(res.data.message || "注册失败");
        }
      } catch (error) {
        console.error("注册出错:", error);
        ElMessage.error("注册失败，请稍后再试");
      } finally {
        registerLoading.value = false;
      }
    }
  });
};
</script>

<style scoped>
.login-container {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(to right, #6366f1, #8b5cf6);
  min-height: 100vh;
  z-index: 1000;
}

.login-box {
  width: 400px;
  padding: 40px;
  color: #fff;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.title {
  text-align: center;
  margin-bottom: 30px;
}

.title h2 {
  font-size: 28px;
  color: #fff;
  margin-bottom: 10px;
  font-weight: 600;
}

.title p {
  color: rgba(255, 255, 255, 0.9);
  font-size: 16px;
}

.form-header {
  text-align: center;
  margin-bottom: 20px;
}

.form-header h3 {
  font-size: 24px;
  color: #fff;
  margin: 0;
}

.login-form,
.register-form {
  width: 100%;
}

.form-footer {
  text-align: center;
  color: rgba(255, 255, 255, 0.9);
}

.form-footer .el-button {
  margin-left: 5px;
}
</style>
